import {createApp} from 'vue'
import type {App as Root} from 'vue'
import {createRouter, createWebHistory} from 'vue-router'
import isInIcestark from '@ice/stark-app/lib/isInIcestark'
import {qiankunWindow, renderWithQiankun} from 'vite-plugin-qiankun/dist/helper'
import HelloWorld from './components/HelloWorld.vue'
import DeviceTest from './components/DeviceTest.vue'
import TestR from './components/TestR.vue'

import App from './App.vue'
import {LifecycleProps} from "@ice/stark-app/lib/registerAppEnter";

let instance: Root<Element> | null = null;

// createApp(App).mount('#app')

// if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
//     console.log(123)
//     render({})
// }

if (!isInIcestark()) {
    render({})
}

function render(props: LifecycleProps | {}) {
    console.log('props', props)
    instance = createApp(App)

    const router = createRouter({
        history: createWebHistory(isInIcestark() ? '/#/microTest/' : ''),
        routes: [
            {
                path: '/hello',
                component: HelloWorld
            },
            {
                path: '/deviceTest',
                component: DeviceTest,
                children: [
                    {
                        path: 'child',
                        component: DeviceTest,
                    }
                ]
            },
            {
                path: '/testR',
                component: TestR
            },

        ]
    })

    instance.use(router)

    instance.mount("container" in props && props.container ? props.container : '#micro-app-vite-vue3');
}

// renderWithQiankun({
//     bootstrap() {
//         console.log("VueMicroApp bootstraped");
//     },
//     mount(props) {
//         console.log("VueMicroApp mount", props);
//         render(props);
//     },
//     unmount() {
//         console.log("VueMicroApp unmount");
//         instance = null;
//     }
// })

export function mount(props: LifecycleProps) {
    render(props)
}

export function unmount(props: any) {
    console.log('props is:', props);
    if (instance) {
        instance.unmount();
        instance = null;
    }
}
